<?php

class Application_Model_UserMapper
{
    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_User');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_User $user)
    {
        $phone = $user->getPhone();
        $data = array(
            'firstName' => $user->getFirstName(),
            'lastName'  => $user->getLastName(),
            'city'      => $user->getCity(),
            'areanum'   => $phone['areanum'] == '' ? null : $phone['areanum'],
            'geonum'    => $phone['geonum'] == '' ? null : $phone['geonum'],
            'localnum'  => $phone['localnum'] == '' ? null : $phone['localnum'],
            'extnum'    => $phone['extnum'] == '' ? null : $phone['extnum'],
            'comment'   => $user->getComment(),
        );

        if (null === ($id = $user->getId())) {
            unset($data['id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function find($id, Application_Model_User $user)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $phone = array(
            'areanum'   => $row->areanum,
            'geonum'    => $row->geonum,
            'localnum'  => $row->localnum,
            'extnum'    => $row->extnum,
        );
        $user->setId($row->id)
            ->setFirstName($row->firstName)
            ->setLastName($row->lastName)
            ->setCity($row->city)
            ->setPhone($phone)
            ->setComment($row->comment);
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_User();
            $phone = array(
                'areanum'   => $row->areanum,
                'geonum'    => $row->geonum,
                'localnum'  => $row->localnum,
                'extnum'    => $row->extnum,
            );
            $entry->setId($row->id)
                ->setFirstName($row->firstName)
                ->setLastName($row->lastName)
                ->setCity($row->city)
                ->setPhone($phone)
                ->setComment($row->comment);
            $entries[] = $entry;
        }
        return $entries;
    }
}

